var taskTableInit = function(){
	var oTableInit = new Object();
    //初始化Table，页面加载时发出请求，获取数据
    oTableInit.Init = function () {
        	$('#taskTable').bootstrapTable({
            url: ctx +'/maintain/maintenanceRecord/listItemRecordByFilter/get.mvc',         //请求后台的URL（*）
            method: 'get',                      //请求方式（*）
//          toolbar: '#toolbar',                //工具按钮用哪个容器
            striped: true,                      //是否显示行间隔色
            cache: false,                       //是否使用缓存，默认为true，所以一般情况下需要设置一下这个属性（*）
            pagination: true,                   //是否显示分页（*）
            paginationLoop:false,
            sortable: true,                     //是否启用排序
            sortOrder: "asc",                   //排序方式
            queryParams: oTableInit.queryParams,//传递参数（*）
            sidePagination: "server",           //分页方式：client客户端分页，server服务端分页（*）
            pageNumber:1,                       //初始化加载第一页，默认第一页
            pageSize: 10,                       //每页的记录行数（*）
            pageList: [10, 25, 50, 100],        //可供选择的每页的行数（*）
            search: false,                       //是否显示表格搜索，此搜索是客户端搜索，不会进服务端，所以，个人感觉意义不大
            strictSearch: true,
            showColumns: false,                  //是否显示所有的列
            showRefresh: false,                  //是否显示刷新按钮
            minimumCountColumns: 2,             //最少允许的列数
            clickToSelect: true,                //是否启用点击选中行
            height: 500,                        //行高，如果没有设置height属性，表格自动根据记录条数觉得表格高度
            uniqueId: "pkId",                     //每一行的唯一标识，一般为主键列
            showToggle:false,                    //是否显示详细视图和列表视图的切换按钮
            cardView: false,                    //是否显示详细视图
            detailView: false,                   //是否显示父子表
            singleSelect:false,                    //禁止多选
            checkboxHeader:true,                 //列头取消多选
            columns: [
            {
            	title: '序号',
            	align : 'center',
                valign : 'middle',
                formatter : function (value, row, index){
                	var options = $('#taskTable').bootstrapTable('getOptions');  
                    return options.pageSize * (options.pageNumber - 1) + index + 1;  
                }
            },
            {
                field: 'equipCode',
                title: '设备编号',
                sortable:false,
                align : 'center',
                valign : 'middle',
                
            },
            {
                field: 'equipName',
                title: '设备名称',
                sortable:false,
                align : 'center',
                valign : 'middle',
                
            },
            {
                field: 'typeCode',
                title: '保养类别编号',
                sortable:false,
                align : 'center',
                valign : 'middle',
                
            },
            {
                field: 'typeName',
                title: '保养类别名称',
                sortable:false,
                align : 'center',
                valign : 'middle',
                
            },
            {
                field: 'itemCode',
                title: '保养项编号',
                sortable:false,
                align : 'center',
                valign : 'middle',
                
            },
            {
                field: 'itemName',
                title: '保养项名称',
                sortable:false,
                align : 'center',
                valign : 'middle',
                
            },
            {
                field: 'maintenanceMethod',
                title: '保养方法',
                sortable:false,
                align : 'center',
                valign : 'middle',
            },
            {
                field: 'stopItem',
                title: '停机项',
                sortable:false,
                align : 'center',
                valign : 'middle',
                formatter : function(value , row ,index){
                	if (value == '0'){
                		return '是';
                	}
                	if (value == '1'){
                		return '否';
                	}
                }
            }, {
                field: 'qualityItem',
                title: '品质项',
                sortable:false,
                align : 'center',
                valign : 'middle',
                formatter : function(value , row ,index){
                	if (value == '0'){
                		return '是';
                	}
                	if (value == '1'){
                		return '否';
                	}
                }
            },
            {
                field: 'createDate',
                title: '保养时间',
                sortable:false,
                align : 'center',
                valign : 'middle',
                formatter : function (value, row, index){
                	if(value==''){
                		return '';
                	}
                    return new Date(value).format('yyyy-MM-dd');
                }
            },
            {
                field: 'maintainUserName',
                title: '保养人',
                sortable:false,
                align : 'center',
                valign : 'middle',

            },
            {
                field: 'maintenanceResult',
                title: '保养结果',
                sortable:false,
                align : 'center',
                valign : 'middle',
                formatter : function (value, row, index){
                	if(value==''){
                		return '';
                	}
                	if(value=='0'){
                		return '已保养';
                	}
                	if(value=='1'){
                		return '未保养';
                	}
                }
            },
            {
                field: 'planId',
                title: 'planId',
                visible:false
            }
            ],

        });
    };	
    //得到查询的参数
    oTableInit.queryParams = function (params) {
        var temp = {   // 这里的键的名字和控制器的变量名必须一直，这边改动，控制器也需要改成一样的
            size: params.limit,   // 页面大小
            num: (params.offset/params.limit) + 1,  // 页码
        	sort: params.sort,
        	order: params.order,
        	equipCode : $("#queryEquipment").val(),
        	equipName : $("#equipName").val(),
        	typeName : $("#typeName").val(),
        	itemName : $("#itemName").val(),
        	startTime : $("#accessTimeStart").val(),
        	endTime : $("#accessTimeEnd").val(),
        };
        return temp;
    };
    return oTableInit;       
};

var TaskInit =function(){
	return {
		//初始化所要执行事件的方法
		init:function(){
			TaskInit._initEquipCodeSelect2("queryEquipment")
			SystemCommon.getSysDict("EQUIP_TYPE","equipType");
			TaskInit.getDateByDay();
			TaskInit.query();
			TaskInit.keyQuery();
			TaskInit.reset();
			TaskInit.refresh();
			TaskInit.doExport();
			TaskInit.changeShortcutTime();
		},
		changeShortcutTime:function () {
            $("#shortcutTime").on("change",function () {
            	var now = new Date(); //当前日期
            	var nowDayOfWeek = now.getDay(); //今天本周的第几天
            	var nowDay = now.getDate(); //当前日
            	var nowMonth = now.getMonth(); //当前月
            	var nowYear = now.getYear(); //当前年
            	nowYear += (nowYear < 2000) ? 1900 : 0; //
            	var lastMonthDate = new Date(); //上月日期
            	lastMonthDate.setDate(1);
            	lastMonthDate.setMonth(lastMonthDate.getMonth() - 1);
            	var lastYear = lastMonthDate.getYear();
            	var lastMonth = lastMonthDate.getMonth();
            	//格式化日期：yyyy-MM-dd
            	function formatDate(date) {
            	    var myyear = date.getFullYear();
            	    var mymonth = date.getMonth() + 1;
            	    var myweekday = date.getDate();
            	    if (mymonth < 10) {
            	        mymonth = "0" + mymonth;
            	    }
            	    if (myweekday < 10) {
            	        myweekday = "0" + myweekday;
            	    }
            	    return (myyear + "-" + mymonth + "-" + myweekday);
            	}
            	//获得某月的天数
            	function getMonthDays(myMonth) {
            	    var monthStartDate = new Date(nowYear, myMonth, 1);
            	    var monthEndDate = new Date(nowYear, myMonth + 1, 1);
            	    var days = (monthEndDate - monthStartDate) / (1000 * 60 * 60 * 24);
            	    return days;
            	}
            	function getPriorSeasonFirstDay(year,month){    
                    var quarterMonthStart=0;    
                    var spring=0; //春    
                    var summer=3; //夏    
                    var fall=6;   //秋    
                    var winter=9;//冬    
                    //月份从0-11    
                    switch(month){//季度的其实月份    
                    case 0:    
                        //如果是第一季度则应该到去年的冬季    
                          year--;    
                          month=spring;    
                        break;    
                    case 1:    
                        month=spring;    
                        break;    
                    case 2:    
                        month=spring;    
                        break;    
                    case 3:    
                        month=summer;    
                        break; 
                    case 4:    
                    	month=summer;    
                        break;    
                    case 5:    
                    	month=summer;    
                    	break;    
                    case 6:    
                    	month=fall;    
                    	break;    
                    case 7:    
                    	month=fall;    
                    	break; 
                    case 8:    
                    	month=fall;    
                    	break;
                    case 9:    
                    	month=winter;    
                    	break;    
                    case 10:    
                    	month=winter;    
                    	break; 
                    case 11:    
                    	month=winter;    
                    	break; 
                    };    
                        
                    return new Date(year,month,1);    
                }; 
                //昨天
                if($("#shortcutTime").val()=="1"){
                	var day1 = new Date();
                	day1.setTime(day1.getTime()-24*60*60*1000);
                	var s1 = day1.getFullYear()+"-" + (day1.getMonth()+1) + "-" + day1.getDate();
                	var start =s1;
                	var end =s1;
        			$('.form_datetimeStart').val(start);
        			$('.form_datetimeEnd').val(end);
                }
                //上周
                if($("#shortcutTime").val()=="2"){
                	var weekStartDate = new Date(nowYear, nowMonth, nowDay - nowDayOfWeek - 6);
                	var weekEndDate = new Date(nowYear, nowMonth, nowDay - nowDayOfWeek - 0);
        			$('.form_datetimeStart').val(formatDate(weekStartDate));
        			$('.form_datetimeEnd').val(formatDate(weekEndDate));
                	 
                }
                //上月
                if($("#shortcutTime").val()=="3"){
                	var lastMonthStartDate = new Date(nowYear, lastMonth, 1);
                	var lastMonthEndDate = new Date(nowYear, lastMonth, getMonthDays(lastMonth));
        			$('.form_datetimeStart').val(formatDate(lastMonthStartDate));
        			$('.form_datetimeEnd').val(formatDate(lastMonthEndDate));
                }
                //上季度
                if($("#shortcutTime").val()=="4"){
                    var priorSeasonFirstDay =getPriorSeasonFirstDay(nowYear, nowMonth);
                    var priorSeasonLastDay = new Date(priorSeasonFirstDay.getFullYear(), priorSeasonFirstDay.getMonth() + 2, getMonthDays(lastMonth));
        			$('.form_datetimeStart').val(formatDate(priorSeasonFirstDay));
        			$('.form_datetimeEnd').val(formatDate(priorSeasonLastDay));
                }
                //上半年
                if($("#shortcutTime").val()=="5"){
                	var priorYearFirstDay = new Date(nowYear, 0, 1);
                	var priorYearEndDay = new Date(nowYear, 5, 30);
        			$('.form_datetimeStart').val(formatDate(priorYearFirstDay));
        			$('.form_datetimeEnd').val(formatDate(priorYearEndDay));
                }
                //去年
                if($("#shortcutTime").val()=="6"){
                    var priorYearFirstDay = new Date(nowYear--, 0, 1);
                    var priorYearLastDay = new Date(nowYear--, 0, 1);
                    console.log(formatDate(priorYearFirstDay));
                    console.log(formatDate(priorYearLastDay));
                    $('.form_datetimeStart').val(formatDate(priorYearLastDay));
        			$('.form_datetimeEnd').val(formatDate(priorYearFirstDay));
                }
            })
        },
		//条件查询
		query : function(){
			$("#queryTask").on("click","",function(){
				$('#taskTable').bootstrapTable('refreshOptions',{
					pageNumber:1,
				});
			});
		},
		//按键触发查询
		keyQuery : function(){
			$(".queryTask").keypress(function (e) {
	            if (e.which == 13) {
	                $("#queryTask").trigger("click");
	            }
	        });
		},
		//重置功能
		reset : function() {
			$(".resetTask").on("click","",function(){
				$(".clearfix input").val("");
				$('.queryEquipment').val(null).trigger("change");
				$('.querySupplier').val(null).trigger("change");
				$('.modelType').val('');
				$('#shortcutTime').val('');
			});
		},
		refresh : function(){
			//刷新
			$("#refreshTask").on("click",function(){
				$('#taskTable').bootstrapTable('refresh');
			});
		},
        //初始化equipCodeSelect2下拉框
        _initEquipCodeSelect2 : function (eleId) {
            var select2 = $("#"+eleId).select2({
                ajax: {
                    url: ctx +'/equipment/register/searchEquipmentByEquipCode/get.mvc',
                    dataType: 'json',
                    data: function (params) {
                        var query = {
                            equipCode: params.term,
                            num: params.page || 1,
                            size:10
                        };
                        return query;
                    },
                    processResults: function (result) {

                        var equipModelArr =new Array();
                        for ( var i = 0; i < result.data.length; i++) {
                            var obj = new Object();
                            obj.id=result.data[i].equipCode;
                            obj.text=result.data[i].equipCode;
                            equipModelArr.push(obj);
                        }
                        var result = {
                            results: equipModelArr,
                            pagination :{
                                more:result.result
                            }
                        };
                        return result;
                    },
                    cache: true
                },
                placeholder: '请选择',
                language: "zh-CN",
                escapeMarkup: function (markup) { return markup; }, // let our custom formatter work
                minimumInputLength: 0
            });
            return select2;
        },
        //时间控件
		getDateByDay : function(e){
			//设置默认时间
			$('.form_datetimeStart').val(new Date(new Date().getTime() - 24*60*60*1000*181).format('yyyy-MM-dd'));
			$('.form_datetimeEnd').val(new Date().format('yyyy-MM-dd'));
			$('.form_datetimeStart').datetimepicker({
                format: 'yyyy-mm-dd',
                minView: 2,
                autoclose: true,
                language: 'zh-CN',
                pickerPosition: "bottom-left",
                //endDate : new Date(),
                forceParse: true
			});
			$('.form_datetimeEnd').datetimepicker({
                format: 'yyyy-mm-dd',
                minView: 2,
                autoclose: true,
                language: 'zh-CN',
                pickerPosition: "bottom-left",
                //endDate : new Date(),
                forceParse: true
			});
		},
		//导出数据
		doExport : function() {
			 $("#exportTaskRecord").on("click","",function(){
				 window.location.href = ctx +"/maintain/maintenanceRecord/exportItemRecord/export.mvc?equipCode="+$("#queryEquipment").val()
				 						+"&equipName="+$("#equipName").val()+"&typeName="+$("#typeName").val()
				 						+"&itemName="+$("#itemName").val()+"&startTime="+$("#accessTimeStart").val()
				 						+"&endTime="+$("#accessTimeEnd").val();
			});
		},
	};
}();

//文档加载完成后激活事件
jQuery(document).ready(function() {
	//1.初始化Table
    var oTable = new taskTableInit();
    //激活table事件
    oTable.Init();
    //初始化页面
    TaskInit.init();
});

